import { useRef } from 'react';

import { useAntdTable } from 'ahooks';
import { Avatar, Button, DatePicker, Input, Popconfirm, Select, Table, Tag } from 'antd';

import Filter from '@/components/filter';
import SearchInput from '@/components/search-input';
import Text from '@/components/text';

import { store } from '@/store';

import { usePermission } from '@/auth';
import { TimeSort } from '@/enum';
import { UserStatusObj, UserTypeObj } from '@/enum/user';
import { orgDeptInfoSetManager } from '@/services/base/bumenguanlibumenxiangguanjiekou';
import {
  orgUserInfoDelete,
  orgUserInfoVoPage
} from '@/services/base/yonghuguanlixitongyonghujiekou';
import { formatValue, parseSrc } from '@/utils';

import Dept from './dept';
import Edit, { EditRef } from './edit';
import EditDept, { EditDeptRef } from './edit-dept';
import EditPassword, { EditPasswordRef } from './edit-password';
import styles from './index.module.scss';

/** 该模块增删改查对象 */
export type BizObject = BASE.OrgUserInfoVOduixiang;

const Page: React.FC = () => {
  const permission = usePermission();
  const edit = useRef<EditRef>(null);
  const editDept = useRef<EditDeptRef>(null);
  const editPassword = useRef<EditPasswordRef>(null);

  const [filter] = Filter.useForm();
  const table = useAntdTable(
    async ({ current, pageSize }, { id, ...formData }) => {
      const res = await orgUserInfoVoPage({
        ...formData,
        ...id,
        page: current,
        size: pageSize,
        timeSort: TimeSort.倒序
      });

      return {
        list: res.data?.records || [],
        total: res.data?.total || 0
      };
    },
    {
      form: filter
    }
  );

  const onSearch = () => {
    table.search.submit();
  };

  const onReset = () => {
    table.search.reset();
  };

  return (
    <>
      <div className={styles['layout']}>
        <div className={styles['sider']}>
          <Dept
            onSelectDeptId={(val: string | undefined) => {
              filter.resetFields();
              console.log(111, val);
              filter.setFieldsValue({
                deptId: val
              });
              table.search.submit();
            }}
          />
        </div>

        <div className={styles['main']}>
          {/* 筛选 */}
          <Filter
            onFinish={onSearch}
            form={filter}
            extra={
              <>
                <Button
                  onClick={() => {
                    edit.current?.open({
                      type: 'add',
                      onSuccess: () => {
                        table.refresh();
                      }
                    });
                  }}
                  type="primary"
                >
                  创建用户
                </Button>
              </>
            }
          >
            <Filter.Item name="deptId" hidden>
              <Input placeholder="请输入部门ID" />
            </Filter.Item>
            <Filter.Item name="id">
              <SearchInput
                style={{
                  width: 120 * 3
                }}
                typeList={[
                  { value: 'username', children: '用户名' },
                  { value: 'id', children: '用户ID' }
                ]}
              />
            </Filter.Item>

            <Filter.Item name="userType">
              <Select
                placeholder="请选择类型"
                allowClear
                options={Array.from(UserTypeObj).map(([key, value]) => ({
                  value: key,
                  label: value.text
                }))}
                style={{ width: 120 }}
              />
            </Filter.Item>

            <Filter.Item name="state">
              <Select
                placeholder="请选择状态"
                allowClear
                options={Array.from(UserStatusObj).map(([key, value]) => ({
                  value: key,
                  label: value.text
                }))}
                style={{ width: 120 }}
              />
            </Filter.Item>

            <Filter.Item name="createTime">
              <DatePicker.RangePicker placeholder={['创建开始时间', '创建结束时间']} />
            </Filter.Item>

            <Filter.Item>
              <Button htmlType="submit" disabled={table.loading}>
                搜索
              </Button>
            </Filter.Item>

            <Filter.Item>
              <Button onClick={onReset} disabled={table.loading}>
                重置
              </Button>
            </Filter.Item>
          </Filter>
          {/* end 筛选 */}

          {/* 表格 */}
          <Table<BizObject>
            columns={[
              {
                title: '序号',
                dataIndex: 'index',
                align: 'center',
                width: 80,
                render: (_text, _record, index) => index + 1
              },
              // {
              //   title: 'id',
              //   dataIndex: 'id'
              // },
              // {
              //   title: '类型',
              //   dataIndex: 'userType',
              //   render: (v) => {
              //     const obj = UserTypeObj.get(v);

              //     if (!obj) {
              //       return emptyText;
              //     }

              //     return <Tag color={obj.color}>{obj.text}</Tag>;
              //   }
              // },
              {
                title: '用户名',
                dataIndex: 'username'
              },
              {
                title: '真实姓名',
                dataIndex: 'fullName'
              },
              {
                title: '头像',
                dataIndex: 'photoUrl',
                render: (v) => {
                  if (v) {
                    return <Avatar src={parseSrc(v)} size={40} />;
                  }

                  return emptyText;
                }
              },
              {
                title: '角色',
                render: (_, row) => {
                  return formatValue(row.roles?.map((v) => v.roleName).join(','));
                }
              },
              {
                title: '部门',
                render: (_, row) => {
                  return formatValue(row.deptInfos?.map((v) => v.deptName).join(','));
                }
              },
              {
                title: '主部门',
                render: (_, row) => {
                  return formatValue(row.mainDeptInfos?.deptName);
                }
              },
              {
                title: '电子邮箱',
                dataIndex: 'email'
              },
              {
                title: '是否为部门主任',
                dataIndex: 'email',
                hidden: !filter?.getFieldValue('deptId'),
                render: (_, row) =>
                  row?.manageDeptIds?.includes(filter?.getFieldValue('deptId')) ? '是' : '否'
              },
              {
                title: '手机号码',
                dataIndex: 'phone'
              },
              {
                title: '状态',
                dataIndex: 'state',
                render: (v) => {
                  const obj = UserStatusObj.get(v);

                  if (!obj) {
                    return emptyText;
                  }

                  return <Tag color={obj.color}>{obj.text}</Tag>;
                }
              },
              {
                title: '创建时间',
                dataIndex: 'createTime'
              },
              {
                title: '修改时间',
                dataIndex: 'updateTime'
              },
              {
                title: '操作',
                fixed: 'right',
                align: 'center',
                render: (_, row) => {
                  return (
                    <Text.Space limit={5}>
                      {permission.check() &&
                        filter?.getFieldValue('deptId') &&
                        !row?.manageDeptIds?.includes(filter?.getFieldValue('deptId')) && (
                          <Popconfirm
                            title={`确定设置为部门主任吗？`}
                            onConfirm={async () => {
                              const res = await orgDeptInfoSetManager({
                                deptId: filter?.getFieldValue('deptId') as unknown as number,
                                userIds: [row.id]
                              });

                              store.app?.message.success(res.message);
                              table.refresh();

                              return res.success;
                            }}
                          >
                            <Text type="primary">设置为部门主任</Text>
                          </Popconfirm>
                        )}
                      {permission.check() && (
                        <Text
                          onClick={() => {
                            editPassword.current?.open({
                              rowData: row,
                              onSuccess: () => {
                                table.refresh();
                              }
                            });
                          }}
                          type="primary"
                        >
                          修改密码
                        </Text>
                      )}

                      {permission.check() && (
                        <Text
                          onClick={() => {
                            edit.current?.open({
                              type: 'edit',
                              rowData: row,
                              onSuccess: () => {
                                table.refresh();
                              }
                            });
                          }}
                          type="primary"
                        >
                          编辑
                        </Text>
                      )}

                      {permission.check() && (
                        <Text
                          onClick={() => {
                            editDept.current?.open({
                              rowData: row,
                              onSuccess: () => {
                                table.refresh();
                              }
                            });
                          }}
                          type="primary"
                        >
                          编辑部门
                        </Text>
                      )}

                      {permission.check() && (
                        <Popconfirm
                          title={`确定删除该角色吗？`}
                          onConfirm={async () => {
                            const res = await orgUserInfoDelete({
                              id: row.id as unknown as string
                            });

                            store.app?.message.success(res.message);
                            table.refresh();

                            return res.success;
                          }}
                        >
                          <Text type="danger">删除</Text>
                        </Popconfirm>
                      )}
                    </Text.Space>
                  );
                }
              }
            ]}
            scroll={{
              x: 'max-content'
            }}
            rowKey="id"
            bordered
            {...table.tableProps}
            pagination={{
              ...table.tableProps.pagination,
              showTotal: (total) => `共 ${total} 条`,
              showQuickJumper: true,
              showSizeChanger: true,
              pageSizeOptions: ['10', '20', '50', '100']
            }}
          />
          {/* end表格 */}
        </div>
      </div>

      <Edit ref={edit} />
      <EditDept ref={editDept} />
      <EditPassword ref={editPassword} />
    </>
  );
};

export default Page;
